package com.nnnu.wsnackshop.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public NotificationWebSocketHandler notificationWebSocketHandler() {
        return new NotificationWebSocketHandler();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册标准WebSocket处理器
        registry.addHandler(notificationWebSocketHandler(), "/api/ws/notifications")
                .setAllowedOrigins("*"); // 允许所有来源

        // 注册SockJS处理器，提高兼容性
        registry.addHandler(notificationWebSocketHandler(), "/api/ws/sockjs/notifications")
                .setAllowedOrigins("*")
                .withSockJS();
    }
}